#! /usr/local/bin/python3

from argparse import ArgumentParser
from datetime import datetime, timedelta
from jdcore import JulianDate, RJulianDate
from decimal import Decimal, InvalidOperation, getcontext
import re
from dateutil import parser

MIN_JULIAN_DATE = Decimal(1721426)
MAX_JULIAN_DATE = Decimal(5373484)
MJD_ZERO = Decimal(2451545)

argparser = ArgumentParser('Convert Datetime and JulianDate')
argparser.add_argument(
    'Time',
    metavar='Time',
    type=str,
    action="store",
    nargs='?',
    help=r"DateTime(UTC) in any resonable format."
)
argparser.add_argument(
    '-M',
    '--Modified',
    action='store_true',
    help='Flag for using Modified Julian Day.'
)
argparser.add_argument(
    '-N',
    '--Now',
    action='store_true',
    help='Return the Julian Day of current time.'
)
argparser.add_argument(
    '-p',
    '--precision',
    action='store',
    type=int,
    default=4,
    help='Set the precision of JulianDay'
)
args = argparser.parse_args()

# 设置JulianDay精度
getcontext().prec = args.precision + 7

# 是否输出当前时间儒略日
if args.Now:
    DateAndTime = datetime.utcnow() # 获取当前UTC时间
    JDate = JulianDate(DateAndTime)
    if args.Modified:
        JDate -= MJD_ZERO
    print(JDate)
else:
    try:
        # Input a Julian Day
        Time = Decimal(args.Time)
        if args.Modified:
            Time += MJD_ZERO
        print(RJulianDate(Time))
    except TypeError as e:      # Empty Input
        argparser.print_help()  # Print help infomation
    except InvalidOperation as e:
        # Not a Julian Day 
        # "default" parameter : processing input without time but with date.
        DateAndTime = parser.parse(args.Time, default=datetime(2000, 1, 1, 12)) 
        JDate = JulianDate(DateAndTime)
        if args.Modified:
            JDate -= MJD_ZERO
        print(JDate)
    except ValueError as e:
        print("Error:", e, 
              "\nPlease enter JulianDate in range [{0}, {1}]".format(MIN_JULIAN_DATE, MAX_JULIAN_DATE))
